package com.application.module.couponget;

import com.application.model.Global;
import com.jfinal.ext.util.DateUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.platform.annotation.Table;
import com.platform.mvc.base.BaseModel;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unused")
@Table(tableName = CouponGet.table_name, pkName = "id")
public class CouponGet extends BaseModel<CouponGet> {

	private static final long serialVersionUID = 6761767368352810428L;

	private static final Log log = Log.getLog(CouponGet.class);
	
	public static final CouponGet dao = new CouponGet().dao();

	/**
	 * 表名称
	 */
	public static final String table_name = "t_coupon_get";

	public static final int TYPE_UNLOCK = 1;//解锁券
    public static final int TYPE_PLAY = 2; //点播券

    /*
    登陆赠送，分享赠送，购买会员赠送
     */
    public static final int SOURCE_LOGIN = 1;
    public static final int SOURCE_SHARE = 2;
    public static final int SOURCE_BUY = 3;
    public static final int SOURCE_NEWUSER = 4;
    public static final int SOURCE_BUYVIP = 5;//参数设置
    static Map<Integer, String> sourceMap = new HashMap<>();
    static {
        sourceMap.put(SOURCE_LOGIN, "登录赠送");
        sourceMap.put(SOURCE_SHARE, "分享赠送");
        sourceMap.put(SOURCE_BUY, "购买点播券");
        sourceMap.put(SOURCE_NEWUSER, "新用户赠送");
        sourceMap.put(SOURCE_BUYVIP, "购买会员赠送");
    }

	/**
	 * sqlId : app.userCoupon.splitPageFrom
	 * 描述：分页from
	 */
	public static final String sqlId_splitPageFrom = "app.couponget.splitPageFrom";

	private Integer id;
	private String name;
	private Integer userid;
	private Integer amount;
	private Integer type;
	private Integer source;
	private Date start_date;
	private Date expire_date;
	private Integer cost;
	private Integer create_userid;
	private Timestamp create_time;
	
	public void setId(Integer id){
		set("id", id);
	}
	public Integer getId() {
		return get("id");
	}
	public void setName(String name){
		set("name", name);
	}
	public String getName() {
		return get("name");
	}
	public void setUserid(Integer userid){
		set("userid", userid);
	}
	public Integer getUserid() {
		return get("userid");
	}
	public void setAmount(Integer amount){
		set("amount", amount);
	}
	public Integer getAmount() {
		return get("amount");
	}
	public void setType(Integer type){
		set("type", type);
	}
	public Integer getType() {
		return get("type");
	}
	public void setSource(Integer source){
		set("source", source);
	}
	public Integer getSource() {
		return get("source");
	}
	public void setExpire_date(Timestamp expire_date){
		set("expire_date", expire_date);
	}
	public Timestamp getExpire_date() {
		return get("expire_date");
	}
	public void setCost(Integer cost){
		set("cost", cost);
	}
	public Integer getCost() {
		return get("cost");
	}
	public void setCreate_userid(Integer create_userid){
		set("create_userid", create_userid);
	}
	public Integer getCreate_userid() {
		return get("create_userid");
	}
	public void setCreate_time(Timestamp create_time){
		set("create_time", create_time);
	}
	public Timestamp getCreate_time() {
		return get("create_time");
	}

    public int findAvailableNum(int userid, int type) {
	    String s = "SELECT COALESCE(sum(amount-cost),0) as amount from " + table_name + " where userid=? and type =? and (expire_date > ? or expire_date is null)";
        return findFirst(s, userid, type, new Date()).getBigDecimal("amount").intValue();
    }

    public void add(int source, int type, int amount, int userid) {
        CouponGet o = new CouponGet();

        if(type == TYPE_UNLOCK) {
            String val = Global.cacheGetByCode(Global.Code.gift_expireDay).getValue();
            if(StrKit.notBlank(val)) {
                long t = System.currentTimeMillis() + 24*3600*1000*Integer.parseInt(val);
                o.setExpire_date(new Timestamp(t));
            }
        }

        o.setAmount(amount);
        o.setCreate_time(new Timestamp(System.currentTimeMillis()));
        o.setCreate_userid(userid);
        o.setSource(source);
//        o.setName(source == SOURCE_LOGIN ? "登录赠送" :(source == SOURCE_SHARE? "分享赠送" : "购买点播券"));
        o.setName(sourceMap.get(source));
        o.setType(type);
        o.set("userid", userid).set("create_day", DateUtil.getCurrentDay());
        o.save();
    }


    public List<CouponGet> findUnlockList(int userid) {
        String s = "SELECT * from " + table_name +
                " where userid=? and type =? and (expire_date > ? or expire_date is null) and amount-cost>0 order by expire_date";
        return find(s, userid, TYPE_UNLOCK, new Date());
    }

    public List<CouponGet> findPlaysList(int userid) {
        String s = "SELECT * from " + table_name +
                " where userid=? and type =? and amount-cost>0 order by expire_date";
        return find(s, userid, TYPE_PLAY);
    }

    public boolean hasSign(Integer userId, int currentDay) {
	    String s = "select count(1) as num from " + table_name + " where userid =? and type =? and create_day = ?";
        return Db.queryLong(s, userId, SOURCE_LOGIN, currentDay) > 0;
    }

    /**
     * 新用户登录时赠送
     * @param userId
     */
    public void addNewUser(Integer userId) {
        int unlockValue = Integer.parseInt(Global.cacheGetByCode(Global.Code.newUser_giftUnlock).getValue());
        int playValue = Integer.parseInt(Global.cacheGetByCode(Global.Code.newUser_giftPlay).getValue());

        add(SOURCE_NEWUSER, TYPE_UNLOCK, unlockValue, userId);
        add(SOURCE_NEWUSER, TYPE_PLAY, playValue, userId);
    }
}
